//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2005
//
// The helper to browse for folder.
//

# include "StdAfx.h"
# include "SelectFolder.h"
# include "Globals.h"

static
int CALLBACK _BrowseCallbackProc (HWND _hWnd, UINT _uMsg, LPARAM _lParam, LPARAM _pData) {
	switch (_uMsg) {
		case BFFM_INITIALIZED:
			//
			// Set the initial folder.
			//
			::SendMessage (_hWnd, BFFM_SETSELECTION, FALSE, _pData);

			//
			// Center the browse window.
			//
			const HWND hParent = ::GetParent (_hWnd);
			if (hParent != NULL) {
				RECT rectParent;
				::GetWindowRect (hParent, & rectParent);

				RECT rect;
				::GetWindowRect (_hWnd, & rect);

				::SetWindowPos (
					_hWnd, NULL,
					(rectParent.right + rectParent.left)/2 - (rect.right - rect.left)/2,
					(rectParent.top + rectParent.bottom)/2 - (rect.bottom - rect.top)/2,
					0, 0,
					SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOSIZE
				);
			}

			break;
/*
		case BFFM_SELCHANGED: {
	  		TCHAR szDir [MAX_PATH];
			if (::SHGetPathFromIDList (reinterpret_cast<LPITEMIDLIST> (_lParam), szDir))
				::SendMessage (_hWnd, BFFM_SETSTATUSTEXT, 0, reinterpret_cast<LPARAM> (szDir));

			break;
		}*/
	}

	return 0;
}

bool SelectFolder (HWND _hWnd, char * _strPath) {
	CComPtr<IMalloc> pMalloc;
	::SHGetMalloc (& pMalloc);

	USES_CONVERSION;

	CComPtr<IShellFolder> pDesktop;
	::SHGetDesktopFolder (& pDesktop);
	LPITEMIDLIST pidlStart = NULL;
	pDesktop->ParseDisplayName (_hWnd, NULL, A2OLE (_strPath), NULL, & pidlStart, NULL);

	LPITEMIDLIST pidlRoot = NULL;
	::SHGetSpecialFolderLocation (_hWnd, CSIDL_DRIVES, & pidlRoot); // "My Computer"

	BROWSEINFO bi;
	::ZeroMemory (& bi, sizeof (bi));
	bi.hwndOwner = _hWnd;
	bi.pidlRoot = pidlRoot;
	bi.pszDisplayName = _strPath;
	bi.lpszTitle = "Please select the folder to save the splitted maps.";
	bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_RETURNFSANCESTORS | BIF_NEWDIALOGSTYLE | /*BIF_STATUSTEXT |*/ BIF_UAHINT;
	bi.lpfn = _BrowseCallbackProc;
	bi.lParam = reinterpret_cast<LPARAM> (pidlStart);
	ITEMIDLIST * const pidl = ::SHBrowseForFolder (& bi);
	pMalloc->Free (pidlRoot);
	pMalloc->Free (pidlStart);
	if (pidl == NULL)
		// Dialog was canceled.
		return false;

	::SHGetPathFromIDList (pidl, _strPath);
	pMalloc->Free (pidl);

	return true;
}